package it.gommonauti.quiz.patente.app;

import it.gommonauti.patenti.entity.CONSTANTS;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
/**
 * 
 * @author gianlucaatwork@gmail.com
 *
 * Overrides the Application class.
 * Useful to save and recover current context or
 * manage device configuration changes
 * 
 */
public class QuizPatenteApplication extends Application implements CONSTANTS {
	
	private static QuizPatenteApplication singleton;
	
	public static QuizPatenteApplication getInstance() {
		return singleton;
	}
	
	@Override
	public final void onCreate() {
		super.onCreate();
		singleton = this;
		
		checkDB();
		
		initialize();
	}
	
	private void checkDB() {
		
		//try { 
		
		String dbUrl = "/data/data/it.gommonauti.quiz.patente.app/db.h2.db";
		
		boolean initialiseDatabase = (new File(dbUrl)).exists();
		if (initialiseDatabase == false) {

		    // Open the .db file in your assets directory
		    InputStream is = null;
		    OutputStream os = null ;
		    
		    try {
		    	
		    	is = singleton.getAssets().open("db.h2.db");

		    	// Copy the database into the destination
		    	os = new FileOutputStream(dbUrl);
		    	byte[] buffer = new byte[1024];
		    	int length;
		    	while ((length = is.read(buffer)) > 0){
		    		os.write(buffer, 0, length);
		    	}
		    	
		    	os.flush();

			    os.close();
			    is.close();
			    
		    } catch (IOException e) {
				
		    	e.printStackTrace();
		    	
			}   
		}
		
	}

	/*
	 * Retrieve configuration: TODO: db?, file system?, .. 
	 */
	private void initialize() {
		
		SharedPreferences sharedPreferences = getSharedPreferences(sharedPreferencesName, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putString(idLanguageKey, "it_IT"); // TODO: retrieve information
		editor.putInt(idQuizStartIndex, 0);
		editor.putInt(idQuizCount, 20);
		editor.commit();
 		
	}

	@Override
	public final void onTerminate() {
		super.onTerminate();
	}
	
	@Override
	public final void onLowMemory(){
		super.onLowMemory();
	}
	
	@Override
	public final void onConfigurationChanged(Configuration newconf) {
		super.onConfigurationChanged(newconf);
	
	}
}
